<template>
  <div>
    <a-form ref="formRef" :model="formState" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <a-form-item label="旧密码" name="oldPassword">
        <a-input-password v-model:value="formState.oldPassword" />
      </a-form-item>
      <a-form-item label="新密码" name="password">
        <a-input-password v-model:value="formState.password" />
      </a-form-item>
      <a-form-item label="确认密码" name="enterpassword">
        <a-input-password v-model:value="formState.enterpassword" />
      </a-form-item>
      <a-form-item :wrapper-col="{ span: 2, offset: 11 }">
        <a-button type="primary" @click="onSubmit" :loading="loading">确定修改</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script setup>
import { reactive, ref, toRaw } from 'vue'
// import { updatapass } from './service'
import { message, Modal } from 'ant-design-vue';
import *  as api from '#/api/core/account';

const formRef = ref()
const labelCol = {
  span: 5
}
const wrapperCol = {
  span: 13
}
const loading = ref(false)
const formState = reactive({
  oldPassword: '',
  password: '',
  enterpassword: ''
})

const validatePass = async (_rule, value) => {
  if (value === '') {
    return Promise.reject('请输入新密码')
  } else if (value != formState.enterpassword) {
    return Promise.reject('新密码和确定密码请保持一致 ')
  } else {
    return Promise.resolve()
  }
}
const validatePass2 = async (_rule, value) => {
  if (value === '') {
    return Promise.reject('请再次输入密码')
  } else if (value != formState.password) {
    return Promise.reject('新密码和确定密码请保持一致 ')
  } else {
    return Promise.resolve()
  }
}
const rules = {
  oldPassword: [
    {
      required: true,
      message: '请输入旧密码',
      trigger: 'change'
    }
  ],
  password: [
    {
      required: true,
      validator: validatePass,
      trigger: ['change', 'blur']
    }
  ],
  enterpassword: [
    {
      required: true,
      validator: validatePass2,
      trigger: ['change', 'blur']
    }
  ]
}

const onSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      loading.value = true
      try {
        await api.$changepassword({
          currentPassword: formState.oldPassword,
          newPassword: formState.password
        })
        message.success('修改成功')
        loading.value = false
        formRef.value.resetFields()
      } catch {
        loading.value = false
      }
    })
    .catch((error) => {
      console.log('error', error)
    })
}
</script>
